package com.team.recovery.listener;

import com.team.recovery.config.RabbitMQConfig;
import com.team.recovery.domain.BizRescueTask;
import com.team.recovery.domain.vo.WebSocketMessageVO;
import com.team.recovery.mapper.BizRescueTaskMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import java.util.*;

/**
 * 救援任务延迟扩大范围监听器
 */
@Component
public class RescueDelayListener {
    @Autowired
    private BizRescueTaskMapper rescueTaskMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    private static final String GEO_MERCHANT_KEY = "geo:merchant";

    @RabbitListener(queues = RabbitMQConfig.RESCUE_DELAY_QUEUE)
    public void onDelayMessage(Map<String, Object> msg) {
        Long taskId = ((Number)msg.get("taskId")).longValue();
        Integer radius = (Integer) msg.get("radius");
        BizRescueTask task = rescueTaskMapper.selectByPrimaryKey(taskId);
        if (task == null || !"0".equals(task.getStatus())) {
            return; // 已被接单或不存在
        }
        // 查询更大范围商家
        GeoOperations<String, String> geoOps = redisTemplate.opsForGeo();
        List<Long> merchantIds = new ArrayList<>();
        geoOps.radius(GEO_MERCHANT_KEY,
                new org.springframework.data.geo.Circle(
                        new org.springframework.data.geo.Point(task.getLongitude().doubleValue(), task.getLatitude().doubleValue()),
                        new org.springframework.data.geo.Distance(radius, org.springframework.data.geo.Metrics.KILOMETERS)))
                .getContent().forEach(r -> merchantIds.add(Long.valueOf(r.getContent().getName())));
        // 推送WebSocket消息给新商家
        WebSocketMessageVO wsMsg = new WebSocketMessageVO();
        wsMsg.setType("rescue_push");
        Map<String, Object> data = new HashMap<>();
        data.put("taskId", task.getId());
        data.put("location", task.getLocation());
        data.put("type", task.getType());
        wsMsg.setData(data);
        for (Long merchantId : merchantIds) {
            simpMessagingTemplate.convertAndSend("/topic/merchant/" + merchantId, wsMsg);
        }
    }
} 